package com.example.rmation.controller;

import com.example.rmation.model.entity.User;
import com.example.rmation.model.request.AddUserRequest;
import com.example.rmation.model.request.UpdateUserRequest;
import com.example.rmation.service.UserService;
import com.example.rmation.utils.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@RequestMapping("/api/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/list")
    public Result studentAllList(@RequestParam Integer pageNum, @RequestParam Integer pageSize, HttpSession session){
        //读取session中是否有用户信息
        User currentUser = (User) session.getAttribute("user");
        //如果没有 返回用户未登录信息
        if (currentUser == null) {
            return Result.error(5000,"您还没有登录");
        }
        //判断登录的是否是教师
        if(currentUser.getRole().equals(2)){
            PageInfo pageInfo = userService.studentAll(pageNum, pageSize);

            return Result.success(pageInfo);
        }else {
            return Result.error(5000,"您不是教师!无法访问学生信息");
        }
    }

    @PostMapping("/add")
    public Result studentAdd(@Valid @RequestBody AddUserRequest addUserRequest, HttpSession session){
        //读取session中是否有用户信息
        User currentUser = (User) session.getAttribute("user");
        //如果没有 返回用户未登录信息
        if (currentUser == null) {
            return Result.error(5000,"您还没有登录");
        }
        //判断是否为教师
        if (currentUser.getRole() == 2) {
            userService.insertUser(addUserRequest);
            return Result.success();
        }else {
            return Result.error(5000,"您不是教师!无法添加学生信息");
        }
    }

    @DeleteMapping("/{id}")
    public Result outOfService(@RequestParam Integer id){
        userService.outOfService(id);
        return Result.success();
    }

    @PostMapping("/update")
    public Result studentUpdate(@Valid @RequestBody UpdateUserRequest updateUserRequest, HttpSession session){
        userService.UpdateUser(updateUserRequest);
        return Result.success();
    }

    @PostMapping("/listLike")
    public Result studentAllLike(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String name, HttpSession session){
        System.out.println(name);
        //读取session中是否有用户信息
        User currentUser = (User) session.getAttribute("user");
        //如果没有 返回用户未登录信息
        if (currentUser == null) {
            return Result.error(5000,"您还没有登录");
        }
        //判断登录的是否是教师
        if(currentUser.getRole().equals(2)){
            PageInfo pageInfo = userService.studentLike(pageNum, pageSize,name);

            return Result.success(pageInfo);
        }else {
            return Result.error(5000,"您不是教师!无法访问学生信息");
        }
    }
}
